﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using YonYou.U8.IN.Forms;
using YonYou.U8.IN.Framework.Actions;
using YonYou.U8.IN.Framework.Internals;
using YonYou.U8.IN.Framework.Provider;
using YonYou.U8.IN.Framework.Views;
using YonYou.U8.IN.Model;

namespace YonYou.U8.IN.Framework
{
    public class WorkBench : IWorkBench
    {
        private BenchView benchView;

        private LayoutView layoutView;

        private ToolBarView toolbarView;

        private StatusBarView statusbarView;

        private ViewBenchForm BenchFrom;

        public Form MainForm
        {
            get
            {
                return benchView.Control as Form;
            }
        }

        internal MetroSkin Skin
        {
            get
            {
                return (benchView.Control as ViewBenchForm).MetroSkin;
            }
        }

        private void InitWorkBench()
        {
            try
            {
                ViewAdvisor.Instance.WorkBench = this;
                benchView = new BenchView();
                ViewAdvisor.Instance.RegisterView(benchView);
                BenchFrom = benchView.Control as ViewBenchForm;
                ((Form)(object)BenchFrom).Load += BenchFrom_Load;
                Application.Idle += Application_Idle;
            }
            catch (Exception ex)
            {
                YonYou.U8.IN.Utility.Debug.WriteLine("[实施导航]-[WorkBench->InitWorkBench]-[StackTrace:{0}]-[Message:{1}]", ex.StackTrace, ex.Message);
            }
        }

        private static string GetNoPermissionMessage()
        {
            switch (ViewAdvisor.Instance.Context.LoginEntity.LanguageID.ToLower())
            {
                case "zh-cn":
                    return "当前用户没有权限,请联系管理员。";
                case "zh-tw":
                    return "當前用戶沒有許可權，請聯繫管理員。";
                case "en-us":
                    return "The current user has not permissions, Please contact your administrator.";
                default:
                    return "当前用户没有权限,请联系管理员。";
            }
        }

        private static bool CheckAuth()
        {
            MenuProvider menuProvider = new MenuProvider();
            BizMenuNode val = menuProvider.Get(ViewAdvisor.Instance.Context.LoginEntity.UFSysConnectionStr);
            if (val == null || ((List<BizNode<BizMenu>>)(object)((BizNode<BizMenu>)(object)val).Childs).Count == 0)
            {
                MessageBoxUtils.ShowTip(GetNoPermissionMessage());
                return false;
            }
            return true;
        }

        private void BenchFrom_Load(object sender, EventArgs e)
        {
            ((Control)(object)BenchFrom).SuspendLayout();
            layoutView = BenchFrom.LayoutView;
            ViewAdvisor.Instance.RegisterView(layoutView);
            statusbarView = new StatusBarView();
            ViewAdvisor.Instance.RegisterView(statusbarView);
            toolbarView = BenchFrom.ToolBarView;
            toolbarView.ExecuteAction<ToolBarInitialize>(new object[0]);
            ViewAdvisor.Instance.RegisterView(toolbarView);
            layoutView.ExecuteAction<LayoutAddView>(new object[2] { LayoutStyle.StatusBar, statusbarView });
            ((Control)(object)BenchFrom).ResumeLayout(false);
        }

        private static bool AutoOpen(string[] args)
        {
            if (args.Length == 0)
            {
                return false;
            }
            Process userProcess = GetUserProcess("ImplementNavigation");
            if (userProcess != null)
            {
                IntPtr mainWindowHandle = userProcess.MainWindowHandle;
                Win32Api.SendMessage(mainWindowHandle, 274, 61728u, 0u);
                Win32Api.SetForegroundWindow(mainWindowHandle);
                Win32Api.SetActiveWindow(mainWindowHandle);
                return true;
            }
            return false;
        }

        private static Process GetUserProcess(string name)
        {
            int sessionId = Process.GetCurrentProcess().SessionId;
            Process currentProcess = Process.GetCurrentProcess();
            Process[] processesByName = Process.GetProcessesByName(name);
            foreach (Process process in processesByName)
            {
                if (process.Id != currentProcess.Id && process.SessionId == sessionId)
                {
                    return process;
                }
            }
            return null;
        }

        public static void RunApplication(string[] args)
        {
            try
            {
                if (!AutoOpen(args)
                    && !Loginable.Instance.CheckIsLogin()
                    && Loginable.Instance.Login(args))
                {
                    ViewAdvisor.Instance.Context = new FrameworkContext();
                    ViewAdvisor.Instance.Context.LoginEntity = Loginable.Instance.LoginEntity;
                    if (CheckAuth())
                    {
                        WorkBench workBench = new WorkBench();
                        workBench.InitWorkBench();
                        Application.Run(workBench.MainForm);
                    }
                }
            }
            catch (Exception ex)
            {
                YonYou.U8.IN.Utility.Debug.WriteLine("[实施导航]-[WorkBench->RunApplication]-[StackTrace:{0}]-[Message:{1}]", ex.StackTrace, ex.Message);
            }
            finally
            {
                Loginable.Instance.Release();
                //WindowShadow.Release();
            }
        }

        private void Application_Idle(object sender, EventArgs e)
        {
            Application.Idle -= Application_Idle;
            ToolBarView toolBarView = ViewAdvisor.Instance.QueryView<ToolBarView>();
            toolBarView.OnSelectingItem();
        }
    }
}
